package online_store.model.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import online_store.entity.CategoryEntity;

import org.springframework.stereotype.Repository;

@Repository
public class CategoryDao {
	
	@PersistenceContext(name="online_store-persistence")
	EntityManager em;
	
	public void createCategory(CategoryEntity category){
		em.persist(category);
	}
	
	public List<CategoryEntity> findAll(){
		List<CategoryEntity> list = new ArrayList<CategoryEntity>();
		
		Query query = em.createQuery("SELECT category FROM CategoryEntity category");
		if(!query.getResultList().isEmpty()){
			list = (List<CategoryEntity>) query.getResultList();
		}

		return list;
	}
	
	public CategoryEntity getCategory(int categoryId){
		CategoryEntity category = null;
		
		Query query = em.createQuery("SELECT category FROM CategoryEntity category WHERE category.category_id=:category_id");
		query.setParameter("category_id", categoryId);
		if(!query.getResultList().isEmpty()){
			category = new CategoryEntity();
			category = (CategoryEntity) query.getSingleResult();
		}

		return category;
	}
	
	public CategoryEntity findByName(String name){
		CategoryEntity category = null;
		
		Query query = em.createQuery("SELECT category FROM CategoryEntity category WHERE category.name=:name");
		query.setParameter("name", name);
		if(!query.getResultList().isEmpty()){
			category = new CategoryEntity();
			category = (CategoryEntity) query.getSingleResult();
		}

		return category;
	}
}
